package com.ttg.web.service.job;

import com.ttg.common.enums.SymbolEnum;
import com.ttg.common.exception.BaseException;
import com.ttg.common.utils.IntegerUtil;
import com.ttg.model.dto.QualityManageReportDTO;
import com.ttg.model.pojo.QualityManageLadderRule;
import com.ttg.model.pojo.QualityManageTypeRule;
import com.ttg.model.pojo.QualityManageWeightConfig;
import com.ttg.web.dao.QualityManageWeightConfigDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Description：
 * Author: chenyou
 * Date: 2025/9/1 15:59
 * Company: ttg
 * Copyright: Copyright (c) 2025
 */
@Slf4j
@Component
public class QualityManageCommon extends JobCommon{

    @Autowired
    private QualityManageWeightConfigDao weightConfigDao;

    @Value("${orgNo:860000000}")
    private Long orgNo;
    /**
     * 加权得分
     * 1.加权计算,结果保留8位小数
     * 2.加权汇总,结果保留2位小数
     */
    public QualityManageReportDTO weightScore(QualityManageReportDTO report, Integer dimType){
        QualityManageWeightConfig weightConfig = weightConfigDao.getByUnique(orgNo,dimType);
        if(report.getRepLivenessScore()!=null && report.getRepClearCostScore()!=null && report.getRepAvgScore()!=null) {
            //加权计算,结果保留8位小数
            BigDecimal livenessScore = report.getRepLivenessScore().multiply(weightConfig.getWcLivenessWeight()).divide(new BigDecimal(100)).setScale(8, BigDecimal.ROUND_HALF_UP);
            BigDecimal clearCostScore = report.getRepClearCostScore().multiply(weightConfig.getWcClearCostWeight()).divide(new BigDecimal(100)).setScale(8, BigDecimal.ROUND_HALF_UP);
            BigDecimal avgScore = report.getRepAvgScore().multiply(weightConfig.getWcAvgWeight()).divide(new BigDecimal(100)).setScale(8, BigDecimal.ROUND_HALF_UP);
            //加权汇总,结果保留2位小数
            BigDecimal weightScore = livenessScore.add(clearCostScore).add(avgScore).setScale(2, BigDecimal.ROUND_HALF_UP);
            report.setRepWeightScore(weightScore);
        }
        return report;
    }

    /**
     * 根据规则类型筛选阶梯规则，匹配阶梯规则下的得分
     */
    public static BigDecimal getRuleScore(Integer ruleType, BigDecimal rate, List<QualityManageLadderRule> rules){
        rules = rules.stream().filter(o -> IntegerUtil.equals(o.getRuleType(),ruleType)).collect(Collectors.toList());
        for(QualityManageLadderRule rule:rules){
            // rate<上限值 && rate>=下限值
            if(rate.compareTo(rule.getRuleUpperBound())<0 && rate.compareTo(rule.getRuleLowerBound())>=0){
                return rule.getRuleScore();
            }
        }
        return BigDecimal.ZERO;
    }


    /**
     * 第二层分类依据判断
     * @param val1 目标值
     * @param val2 条件值
     * @param symbol 条件符号 包括(>,>=,==,<=,<,!=)
     * @return: boolean
     * @date: 2025/9/2 15:14
     * @author: chenyou
     */
    public static boolean twoJudge(BigDecimal val1,BigDecimal val2,String symbol){
        if(SymbolEnum.getByVal(symbol)==null){
            throw new BaseException("错误的比较符号");
        }
        boolean result = false;
        switch (SymbolEnum.getByVal(symbol)){
            case 大于:
                result = val1.compareTo(val2)>0;
                break;
            case 大于等于:
                result = val1.compareTo(val2)>=0;
                break;
            case 等于:
                result = val1.compareTo(val2)==0;
                break;
            case 小于等于:
                result = val1.compareTo(val2)<=0;
                break;
            case 小于:
                result = val1.compareTo(val2)<0;
                break;
            case 不等于:
                result = val1.compareTo(val2)!=0;
                break;
        }
        return result;
    }

    public static Long calculateQtrId(QualityManageReportDTO reportDTO, List<QualityManageTypeRule> rules){
        Long qtrId = null;
        BigDecimal weightScore = reportDTO.getRepWeightScore();
        BigDecimal livenessScore = reportDTO.getRepLivenessScore();
        BigDecimal clearCostScore = reportDTO.getRepClearCostScore();
        BigDecimal avgScore = reportDTO.getRepAvgScore();

        //2. 根据分类运算公式对行业进行质量指导分类
        for (QualityManageTypeRule rule : rules){
            boolean main = false;
            boolean sub1 = true;
            boolean sub2 = true;
            boolean sub3 = true;
            //2.1 一层分类判断 weightScore<上限值 && weightScore>=下限值,满足条件才做第二层分类判断
            if(weightScore.compareTo(rule.getQtrUpperBound())<0 && weightScore.compareTo(rule.getQtrLowerBound())>=0){
                main = true;
                //2.2 若存在二层分类则继续判断,需对可能存在的活跃率,清算成本,户均归集条件进行判断
                //2.2.1 活跃率条件判断
                if(Objects.nonNull(rule.getQtrSubLiveness())){
                    sub1 = twoJudge(livenessScore,rule.getQtrSubLiveness(),rule.getQtrSubLivenessSymbol());
                }
                //2.2.2 清算成本条件判断
                if(Objects.nonNull(rule.getQtrSubClearCost())){
                    sub2 = twoJudge(clearCostScore,rule.getQtrSubClearCost(),rule.getQtrSubClearCostSymbol());
                }
                //2.2.3 户均归集条件判断
                if(Objects.nonNull(rule.getQtrSubAvg())){
                    sub3 = twoJudge(avgScore,rule.getQtrSubAvg(),rule.getQtrSubAvgSymbol());
                }

            }else{
                main = false;
            }

            if(main && sub1 && sub2 && sub3){
                qtrId = rule.getQtrId();
                break;
            }
        }
        return qtrId;
    }
}
